package com.jnu.supermarket.data;

import android.content.Context;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DataBank {
    public static final String DATA_FILE_NAME = "data";
    private final Context context;
    List<ShopItem> shopItemList;//定义结构体

    public DataBank(Context context) {
        this.context=context;
    }

    public List<ShopItem> loadData() {
        shopItemList = new ArrayList<>();
        try{
            ObjectInputStream objectInputStream=new ObjectInputStream(context.openFileInput(DATA_FILE_NAME));
            shopItemList=(ArrayList<ShopItem>) objectInputStream.readObject();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return shopItemList;
    }

    public void saveData() {
        //在保存时，将结构体序列化
        ObjectOutputStream objectOutputStream=null;
        try{
            objectOutputStream = new ObjectOutputStream(context.openFileOutput(DATA_FILE_NAME, Context.MODE_PRIVATE));
            objectOutputStream.writeObject(shopItemList);
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally {
            try{
                if(objectOutputStream!=null){
                    objectOutputStream.close();
                }
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}
